﻿using FileSC.Configs;
using Hangfire;
using Hangfire.LiteDB;
using System;
using System.IO;

namespace FileSC.Hangfire
{
    public class HangfireService : IHangfireService
    {
        internal BackgroundJobServer backgroundJobServer;
        public void Init()
        {
            var db = AppConfig.Text("任务数据库");
            var db_path = Path.GetFullPath(db);
            Directory.CreateDirectory(Path.GetDirectoryName(db_path));
            GlobalConfiguration.Configuration
               .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
               .UseSimpleAssemblyNameTypeSerializer()
               .UseRecommendedSerializerSettings()
               .UseDefaultTypeSerializer()
               .UseLiteDbStorage($"FileName={db};connection=shared", new LiteDbStorageOptions
               {
                   // 决定的会不会立即执行BackgroundJob
                   InvisibilityTimeout = TimeSpan.FromMinutes(1),
                   DistributedLockLifetime = TimeSpan.FromSeconds(30),
                   QueuePollInterval = TimeSpan.FromSeconds(1),
                   CountersAggregateInterval = TimeSpan.FromMinutes(3),
                   JobExpirationCheckInterval = TimeSpan.FromHours(1),
               });

            var queues = AppConfig.Array("任务队列");
            var workerCount = int.Parse(AppConfig.Text("任务并行数"));
            backgroundJobServer = new BackgroundJobServer(new BackgroundJobServerOptions
            {
                Queues = queues,
                WorkerCount = Math.Max(Environment.ProcessorCount, workerCount),
            });
            // 全局重试次数
            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 });

            BackgroundJob.Enqueue(() => Console.WriteLine("HANGFIRE LOADED!"));
        }

    }
}
